package com.cy.src.common.helper;

import android.util.Log;

import java.io.File;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by CY on 2016/5/19.
 */
public class UploadHelper {

    /**
     * 多文件上传
     *
     * @param uploadHost 上传文件的url
     * @param filePaths 文件绝对路径数组
     * @return 返回可观察对象，携带请求返回的结果，在子线程执行。
     */
    public static Observable<String> upload(final String uploadHost, final String... filePaths) {

        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onStart();
                try {
                    Call call = upload2(uploadHost, filePaths);
                    Response response = call.execute();
                    String json = response.body().string();
                    subscriber.onNext(json);
                } catch (Exception e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.newThread());
    }

    private static Call upload2(String uploadHost, String... filePaths) {

        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        for (String path : filePaths) {
            File file = new File(path);
            builder.addFormDataPart("image", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file));
            Log.e("upload", "path=" + path);
        }

        Request request = new Request.Builder()
                .url(uploadHost)//"http://120.31.131.105:8003/BangFu/File/Upload2"
                .post(builder.build())
                .build();
        return client.newCall(request);
    }
}

